package net.cassandraview;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import net.cassandraview.config.Host;

@ManagedBean(name = "indexPage")
@ViewScoped
public class IndexPage implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@ManagedProperty("#{userSession}")
	private UserSession session;
	
	private String newHost;
	
	private Integer newPort;
	
	private Integer newJmxPort;
	
	private String newUserName;
	
	private String newPassword;
	
	private Integer tableIndex;
	
	private List<Host> recentHosts;
	
	@PostConstruct
	protected void init() {
		recentHosts = session.getRecentConnections();
	}
	
	public void makeNewConnection() {
		Host h = new Host();
		h.setHost(newHost);
		h.setPort(newPort.toString());
		h.setJmxPort(newJmxPort.toString());
		session.reconnect(h);
		recentHosts = session.getRecentConnections();
	}
	
	public void reconnect() {
		if (tableIndex != null && tableIndex >= 0 && tableIndex < recentHosts.size()) {
			Host h = recentHosts.get(tableIndex);
			session.reconnect(h);
			recentHosts = session.getRecentConnections();
		}
	}
	
	public String getIndexHost() {
		if (tableIndex != null && tableIndex >= 0 && tableIndex < recentHosts.size()) {
			Host h = recentHosts.get(tableIndex);
			return h.getHost() + ":" + h.getPort() + "/" + h.getJmxPort();
		}
		return "";
	}

	public String getNewHost() {
		return newHost;
	}

	public void setNewHost(String newHost) {
		this.newHost = newHost;
	}

	public Integer getNewPort() {
		return newPort;
	}

	public void setNewPort(Integer newPort) {
		this.newPort = newPort;
	}

	public Integer getNewJmxPort() {
		return newJmxPort;
	}

	public void setNewJmxPort(Integer newJmxPort) {
		this.newJmxPort = newJmxPort;
	}

	public String getNewUserName() {
		return newUserName;
	}

	public void setNewUserName(String newUserName) {
		this.newUserName = newUserName;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public List<Host> getRecentHosts() {
		return recentHosts;
	}

	public void setRecentHosts(List<Host> recentHosts) {
		this.recentHosts = recentHosts;
	}

	public UserSession getSession() {
		return session;
	}

	public void setSession(UserSession session) {
		this.session = session;
	}

	public Integer getTableIndex() {
		return tableIndex;
	}

	public void setTableIndex(Integer tableIndex) {
		this.tableIndex = tableIndex;
	}
	
}
